from django import forms
from django.core import validators
from .models import Article
# 留言板的表单
class MessageForm(forms.Form):
    title = forms.CharField(min_length=2, max_length=20, label='标题', error_messages={
        "min_length": "标题不能少于2个字符",
        "max_length": "标题不能超过20个字符"
    })
    content = forms.CharField(min_length=2, max_length=200, label='内容', widget=forms.Textarea)
    email = forms.EmailField(label='邮箱',)
# 正则表达式验证器
class RegisterForm(forms.Form):
    telephone = forms.CharField(validators=[validators.RegexValidator(r'^1[3456789]\d{9}$', message='手机号格式不正确')], label='手机号')
    pw1 = forms.CharField(min_length=6, max_length=20,)
    pw2 = forms.CharField(min_length=6, max_length=20,)
    # 通过某个字段名进行验证
    def clean_telephone(self):
        telephone = self.cleaned_data.get('telephone')
        # 从数据库中查找telephone是否存在,如果存在,那么抛出验证错误
        if telephone == '19999999999':
            raise forms.ValidationError('手机号已存在')
        else:
            return telephone
    def clean(self):# 通过clean方法进行验证
        cleaned_data = super().clean()
        pw1 = cleaned_data.get('pw1')
        pw2 = cleaned_data.get('pw2')
        if pw1 != pw2:# 如果输入不一致,那么抛出验证错误
            raise forms.ValidationError('两次输入的密码不一致')
        else:
            return cleaned_data

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        # 指模型中所有的字段
        fields = '__all__'
        # 指定需要的字段
        # filter = ['title', 'content']
        error_messages ={
            'category':{
                'required': 'category不能为空'
            }
        }
